package cn.itcast.bos.web.action;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.utils.MailUtils;
import cn.itcast.bos.utils.UUIDUtils;
import cn.itcast.crm.domain.Customer;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.servlet.http.HttpSession;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: SOS
 * @create: 2018-02-24 21:36
 */

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer> {

    @Autowired
    @Qualifier("jmsQueueTemplate")
    private JmsTemplate jmsTemplate;


    @Action(value = "customer_sendSms")
    public String sendSms() throws Exception {
        //手机号保存在customer中,生成短信验证码
        final String randomCode = RandomStringUtils.randomNumeric(6);
        //将短信验证码保存到session中
        ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode);
        System.out.println("生成的手机验证码为:" + randomCode);
        //编辑短信内容
        final String msg = "尊敬的用户您好,本次获取的验证码为:" + randomCode + "服务电话为:400-888-8888";
        //String result = SmsUtils.sendSmsByHTTP(model.getTelephone(),msg);
        /*String result = "000/xxx";
        if (result.startsWith("000")) {
            //说明发送成功
            return NONE;
        }else {
            throw new RuntimeException("短信发送失败,信息码为:"+result);
        }*/
        //调用activeMQ发送
        jmsTemplate.send("bos_sms", new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                MapMessage mapMessage = session.createMapMessage();
                mapMessage.setString("telephone", model.getTelephone());
                mapMessage.setString("msg", msg);
                return mapMessage;
            }
        });

        return NONE;

    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    //属性驱动接受验证码
    private String checkcode;

    public void setCheckcode(String checkcode) {
        this.checkcode = checkcode;
    }

    //用户注册功能
    @Action(value = "customer_regist", results = {@Result(name = "success", location = "./signup-success.html", type
            = "redirect"),
            @Result(name = "input", location = "./signup.html", type = "redirect")})
    public String regist() {
        String checkcodeSession = (String) ServletActionContext.getRequest().getSession().getAttribute(model
                .getTelephone());
        if (checkcodeSession == null || !checkcodeSession.equalsIgnoreCase(checkcode)) {
            System.out.println("短信验证码错误...");
            return INPUT;
        }
        WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/customer").type(MediaType
                .APPLICATION_JSON).post(model);
        System.out.println("用户注册成功");
        //生成一个激活码
        String activecode = UUIDUtils.getUUID();
        System.out.println(activecode);
        redisTemplate.opsForValue().set(model.getTelephone(), activecode, 24, TimeUnit.HOURS);
        String content = "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='"
                + MailUtils.activeUrl + "?telephone=" + model.getTelephone()
                + "&activecode=" + activecode + "'>速运快递邮箱绑定地址</a>";

        MailUtils.sendMail("速运快递激活邮件", content, model.getEmail());


        return SUCCESS;
    }

    private String activecode;

    public void setActivecode(String activecode) {
        this.activecode = activecode;
    }

    @Action(value = "customer_activeMail")
    public String activeMail() throws IOException {

        //获取激活码
        ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
        String activecodeRedis = redisTemplate.opsForValue().get(model.getTelephone());
        if (activecodeRedis == null || !activecodeRedis.equalsIgnoreCase(activecode)) {
            //激活码无效
            ServletActionContext.getResponse().getWriter().write("激活码无效,请重新激活!");
        } else {
            //激活码有效
            //防止重复绑定
            //调用crm webservice 查询客户信息,判断是否已绑定
            Customer customer = WebClient.create
                    (Constants.CRM_MANAGEMENT_URL+"/services/customerService/customer/telephone/" +
                            model.getTelephone()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
            if (customer.getType() == null || customer.getType() != 1) {
                //customer没激活,调用方法激活该账号
                WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/updateType/" +
                        model.getTelephone()).accept(MediaType.APPLICATION_JSON).get();
                ServletActionContext.getResponse().getWriter().write("恭喜你,绑定成功");
            } else {
                //激活了
                ServletActionContext.getResponse().getWriter().write("邮箱已经激活,不要多次激活");
            }

            //登录以后以后删除激活码
            redisTemplate.delete(model.getTelephone());

        }


        return NONE;
    }

    /**
     * //用户登录
     * @return
     */
    @Action(value = "customer_login", results = {@Result(name = SUCCESS, location = "./index.html#/myhome", type =
            "redirect"),
            @Result(name = "error", location = "./index.html", type = "redirect")})
    public String customerLogin() {
        //customer在crm系统中,必须提供webservice服务
        Customer customer = WebClient
                .create(Constants.CRM_MANAGEMENT_URL
                        + "/services/customerService/customer/login?telephone="
                        + model.getTelephone() + "&password="
                        + model.getPassword())
                .accept(MediaType.APPLICATION_JSON).get(Customer.class);
        System.out.println(customer);
        if (customer == null) {
            // 登录失败
            return ERROR;
        } else {
            // 登录成功
            HttpSession session = ServletActionContext.getRequest().getSession();
            session.setAttribute("customer", customer);
            return SUCCESS;
        }
    }

}
